import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";

export const layoutChildren: Array<RouteRecordRaw> = [
  {
    path: "/home",
    name: "home",
    meta: {
      title: "首页",
    },
    component: () =>
      import(/* webpackChunkName: "home" */ "@/views/home/indexView.vue"),
  },
  {
    path: "/friend",
    name: "friend",
    meta: {
      title: "车友圈",
    },
    component: () =>
      import(/* webpackChunkName: "friend" */ "@/views/friend/indexView.vue"),
  },
  {
    path: "/select/car",
    name: "selectCar",
    meta: {
      title: "选车",
    },
    component: () =>
      import(
        /* webpackChunkName: "selectCar" */ "@/views/selectCar/indexView.vue"
      ),
  },
  {
    path: "/old/car",
    name: "oldCar",
    meta: {
      title: "二手车",
    },
    component: () =>
      import(/* webpackChunkName: "oldCar" */ "@/views/oldCar/indexView.vue"),
  },
  {
    path: "/serve",
    name: "serve",
    meta: {
      title: "服务",
    },
    component: () =>
      import(/* webpackChunkName: "serve" */ "@/views/serve/indexView.vue"),
  },
];

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    name: "layout",
    redirect: "/home",
    component: () =>
      import(/* webpackChunkName: "layout" */ "@/views/layout/indexView.vue"),
    children: layoutChildren,
  },
  {
    path: "/detail/:id",
    name: "detail",
    component: () => import("@/views/detail/indexView.vue"),
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/login/indexView.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});


router.beforeEach((to, from) => {
  const token = localStorage.getItem('token');
  
  if(token) {
    // 已经登录
    if(to.path === '/login') return { name: 'home' }
  } else {
    // 未登录
    if(to.path !== '/login') return { name: 'login' }
  }
})

export default router;
